package com.doudanhua.basecode.controller;

import com.doudanhua.basecode.dto.DogDto;
import com.doudanhua.basecode.jpa.entity.School;
import com.doudanhua.basecode.jpa.repository.SchoolReposiroty;
import com.doudanhua.basecode.rabbitmq.MqHelper;
import com.doudanhua.basecode.rabbitmq.RabbitMqConfig;
import com.doudanhua.basecode.redis.RedisLock;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @Author zhangqian
 * @Description TODO
 * @Date 2022/11/8 17:10
 */
@RestController
@RequestMapping("demo")
public class DemoController {
    private final MqHelper mqHelper;
    private final RedisLock redisLock;
    private final SchoolReposiroty schoolReposiroty;

    public DemoController(MqHelper mqHelper, RedisLock redisLock, SchoolReposiroty schoolReposiroty) {
        this.mqHelper = mqHelper;
        this.redisLock = redisLock;
        this.schoolReposiroty = schoolReposiroty;
    }


    @PostMapping("mq/send")
    public void mqSend() {
        mqHelper.send(RabbitMqConfig.EXCHANGE_BASECODE, RabbitMqConfig.KEY_BASECODE, new DogDto());
    }


    @PostMapping("mq/delay/send")
    public void mqDelaySend() {
        mqHelper.delayedSend(RabbitMqConfig.EXCHANGE_DELAYED, RabbitMqConfig.KEY_BASECODE, new DogDto(), 5);
    }

    @PostMapping("lock/test/{time}")
    public void lockTest(@PathVariable long time) throws Exception {
        String key = "lock.key";
        redisLock.lock(key, time, TimeUnit.SECONDS, () -> {
            try {
                Thread.sleep(1000 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        });
    }

    @PostMapping("lock/test2/{time}")
    public void lockTest2(@PathVariable long time) throws Exception {
        String key = "lock.key";
        redisLock.lock(key, time, TimeUnit.SECONDS, () -> {
            try {
                Thread.sleep(10 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        });
    }

    @PostMapping("jpa/save")
    public School jap_save(@RequestBody School school) {
        final School save = schoolReposiroty.save(school);
        return save;
    }
}
